<template>
  <div class="wrap" :style="`height: ${height}`">
    <Run
      v-if="data.form"
      class="apply-form"
      approve
      :form="data.form"
      :comps="data.comps"
      :data-value="data.dataValue"
      :taskKey="taskKey"
      :loading="state.loading"
      @approve="handleApprove"
      @close="handleClose"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import Run from '@/components/form-engine/run/index.vue'
import { util } from '@/utils'
import type { DesignItemStruct } from '@/typings'
import { formRunApi } from '@/api/modules/flow/formRun'
import type { FormInstance } from '@/api/modules/flow/formRun'
import { useTagStore } from '@/stores/tag'

const height = computed(() => `${util.getContentHeight()}px`)

const route = useRoute() //{ fid: '', tid: '', tkey: '' }
const data = reactive<{ form: Record<string, any>; comps: DesignItemStruct[]; dataValue: any }>({} as any)
const state = reactive({ loading: false, permission: {} as any })

const taskKey = computed(() => route.query.tkey as string)
const getStructure = () => {
  formRunApi.findById(route.query.fid as string).then(resp => {
    if (resp.success) {
      if (resp.data) {
        if (resp.data.formJson) {
          const json = JSON.parse(resp.data.formJson)
          data.form = json.form
          data.comps = json.comps
        }
        if (resp.data.formValue) {
          data.dataValue = JSON.parse(resp.data.formValue)
        }
      }
    }
  })
}
onMounted(getStructure)

const handleApprove = ({ flowParams, formValue }: any) => {
  const formInstance = {
    formValue,
    formInstanceId: route.query.id as string
  } as FormInstance
  state.loading = true
  const params = { taskId: route.query.tid as string, formInstance, variables: flowParams }
  formRunApi.approve(params).then(resp => {
    state.loading = false
    if (resp.success) {
      ElMessage.success('表单已提交')
    }
  })
}

const router = useRouter()
const tagStore = useTagStore()
const handleClose = () => {
  tagStore.closeCurrent(router)
}
</script>

<style lang="scss" scoped>
.wrap {
  background-color: $--color-bg-gray;
  margin: -15px;
  padding: 0 10%;
  padding-bottom: 25px;
  .apply-form {
    box-shadow: 5px 10px 5px rgba(0, 0, 0, 0.05);
    border-radius: 4px;
  }
}
</style>
